<!DOCTYPE html>
<html lang="zh-Hans">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/blog/images/logo.svg" color="#222">

<link rel="stylesheet" href="/blog/css/main.css">


<link rel="stylesheet" href="/blog/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"yoursite.com","root":"/blog/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="开始使用 retrofit本身是对网络请求的再封装,所以需要其它网络请求库的支持比如Okhttpconverter-gson是json的转换器  在app的build.gradle下添加依赖: 123compile &#39;com.squareup.okhttp3:okhttp:3.8.1&#39;compile &#39;com.squareup.retrofit2:retrofit:2.3.0&#39;compile &#39;c">
<meta property="og:type" content="article">
<meta property="og:title" content="Retorfit菜鸟使用入门">
<meta property="og:url" content="http://yoursite.com/2017/08/09/retroift/index.html">
<meta property="og:site_name" content="二松同学">
<meta property="og:description" content="开始使用 retrofit本身是对网络请求的再封装,所以需要其它网络请求库的支持比如Okhttpconverter-gson是json的转换器  在app的build.gradle下添加依赖: 123compile &#39;com.squareup.okhttp3:okhttp:3.8.1&#39;compile &#39;com.squareup.retrofit2:retrofit:2.3.0&#39;compile &#39;c">
<meta property="article:published_time" content="2017-08-09T09:01:56.000Z">
<meta property="article:modified_time" content="2020-06-23T03:08:32.949Z">
<meta property="article:author" content="二松">
<meta property="article:tag" content="android">
<meta property="article:tag" content="网络">
<meta property="article:tag" content="retrofit">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://yoursite.com/2017/08/09/retroift/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-Hans'
  };
</script>

  <title>Retorfit菜鸟使用入门 | 二松同学</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/blog/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">二松同学</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">拥有梦想只是一种智力，实现梦想才是一种能力</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/blog/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/blog/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/blog/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/blog/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/blog/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-Hans">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2017/08/09/retroift/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
      <meta itemprop="name" content="二松">
      <meta itemprop="description" content="good good study day day up.">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="二松同学">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Retorfit菜鸟使用入门
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2017-08-09 17:01:56" itemprop="dateCreated datePublished" datetime="2017-08-09T17:01:56+08:00">2017-08-09</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-06-23 11:08:32" itemprop="dateModified" datetime="2020-06-23T11:08:32+08:00">2020-06-23</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/%E6%8A%80%E6%9C%AF%E5%8D%9A%E5%AE%A2/" itemprop="url" rel="index"><span itemprop="name">技术博客</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h2 id="开始使用"><a href="#开始使用" class="headerlink" title="开始使用"></a>开始使用</h2><blockquote>
<p>retrofit本身是对网络请求的再封装,所以需要其它网络请求库的支持比如Okhttp<br>converter-gson是json的转换器</p>
</blockquote>
<p>在app的build.gradle下添加依赖:</p>
<figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">compile <span class="string">'com.squareup.okhttp3:okhttp:3.8.1'</span></span><br><span class="line">compile <span class="string">'com.squareup.retrofit2:retrofit:2.3.0'</span></span><br><span class="line">compile <span class="string">'com.squareup.retrofit2:converter-gson:2.3.0'</span></span><br></pre></td></tr></table></figure>


<h2 id="初始化Retrofit"><a href="#初始化Retrofit" class="headerlink" title="初始化Retrofit"></a>初始化Retrofit</h2><blockquote>
<p>新建Retrofit网络请求客户端,并进行配置<br>深度的配置可以传入OkhttpClient后面会提到部分</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Retrofit retrofit = <span class="keyword">new</span> Retrofit.Builder()</span><br><span class="line">            .baseUrl(<span class="string">"url"</span>)<span class="comment">//服务器地址</span></span><br><span class="line">            .addConverterFactory(GsonConverterFactory.create())<span class="comment">//json转换器,可以自定义</span></span><br><span class="line">            .build();</span><br></pre></td></tr></table></figure>
<h2 id="创建Get请求"><a href="#创建Get请求" class="headerlink" title="创建Get请求"></a>创建Get请求</h2><blockquote>
<p>Retrofit的请求都是通过创建接口,并通过方法上的注解获取需要的参数</p>
<p>@GET表示get请求方式,()内可以传入接口地址</p>
<p>@Query后接get请求的参数,将会拼接到地址后</p>
<p>@QueryMap后接一个map,map存放参数,适合参数较多的情况</p>
<p>Call是网络请求的操作对象,泛型指定了返回的数据类型</p>
</blockquote>
<ol>
<li><p>创建请求接口  </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">DemoApi</span> </span>&#123;	</span><br><span class="line"><span class="meta">@GET</span>(<span class="string">"url"</span>)</span><br><span class="line"><span class="function">Call&lt;ResponseBody&gt; <span class="title">get1</span><span class="params">(@Query(<span class="string">"var1"</span>)</span> String var1,@<span class="title">Query</span><span class="params">(<span class="string">"var2"</span>)</span> String var2)</span>;</span><br><span class="line"></span><br><span class="line"><span class="meta">@GET</span>(<span class="string">"url"</span>)</span><br><span class="line"><span class="function">Call&lt;ResponseBody&gt; <span class="title">get2</span><span class="params">(@QueryMap Map&lt;String, String&gt; vars)</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>生成接口,获得Call对象</p>
<blockquote>
<p>如果不想传递某个参数,参数值为null即可</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">DemoApi demoApi = retrofit.create(DemoApi<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line"><span class="comment">//@Query</span></span><br><span class="line">Call&lt;ResponseBody&gt; call = demoApi.get1(<span class="string">"var1"</span>,<span class="string">"var2"</span>);</span><br><span class="line"><span class="comment">//@QueryMap</span></span><br><span class="line">Map&lt;String, String&gt; vars = <span class="keyword">new</span> HashMap&lt;&gt;();</span><br><span class="line">vars.put(<span class="string">"var1"</span>,<span class="string">"var1"</span>);</span><br><span class="line">vars.put(<span class="string">"var2"</span>,<span class="string">"var2"</span>);</span><br><span class="line">Call&lt;ResponseBody&gt; call = demoApi.get2(vars);</span><br></pre></td></tr></table></figure>


</li>
</ol>
<h2 id="创建post请求"><a href="#创建post请求" class="headerlink" title="创建post请求"></a>创建post请求</h2><blockquote>
<p>@POST代表这个方法是post请求</p>
<p>@FormUrlEncoded表示将表单内的数据处理为键值对</p>
<p>@Field后接需要传递的参数</p>
<p>@FieldMap适用于参数较多的情况,可以放参数放到一个map中</p>
</blockquote>
<ol>
<li><p>创建请求接口  </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">DemoApi</span> </span>&#123;	</span><br><span class="line"><span class="meta">@FormUrlEncoded</span></span><br><span class="line"><span class="meta">@POST</span>(<span class="string">"url"</span>)</span><br><span class="line"><span class="function">Call&lt;ResponseBody&gt; <span class="title">post1</span><span class="params">(@Field(<span class="string">"var1"</span>)</span> String var1,@<span class="title">Field</span><span class="params">(<span class="string">"var2"</span>)</span> String var2)</span>;</span><br><span class="line">&#125;</span><br><span class="line">  </span><br><span class="line"><span class="meta">@FormUrlEncoded</span></span><br><span class="line"><span class="meta">@POST</span>(<span class="string">"url"</span>)</span><br><span class="line"><span class="function">Call&lt;ResponseBody&gt; <span class="title">post2</span><span class="params">(@FieldMap Map&lt;String, String&gt; vars)</span></span>;</span><br></pre></td></tr></table></figure>
</li>
<li><p>生成接口,获得Call对象</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">DemoApi demoApi = retrofit.create(DemoApi<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line"><span class="comment">//@Field</span></span><br><span class="line">Call&lt;ResponseBody&gt; call = demoApi.post1(<span class="string">"var1"</span>,<span class="string">"var2"</span>);</span><br><span class="line"><span class="comment">//@FieldMap</span></span><br><span class="line">Map&lt;String, String&gt; vars = <span class="keyword">new</span> HashMap&lt;&gt;();</span><br><span class="line">vars.put(<span class="string">"var1"</span>,<span class="string">"var1"</span>);</span><br><span class="line">vars.put(<span class="string">"var2"</span>,<span class="string">"var2"</span>);</span><br><span class="line">Call&lt;ResponseBody&gt; call = demoApi.post2(vars);</span><br></pre></td></tr></table></figure>

</li>
</ol>
<h2 id="如何请求"><a href="#如何请求" class="headerlink" title="如何请求"></a>如何请求</h2><h3 id="发起请求"><a href="#发起请求" class="headerlink" title="发起请求"></a>发起请求</h3><ol>
<li><p>同步请求</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Response&lt;ResponseBody&gt; response = call.execute();</span><br></pre></td></tr></table></figure>
</li>
<li><p>异步请求</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">call.enqueue(<span class="keyword">new</span> Callback&lt;ResponseBody&gt;() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onResponse</span><span class="params">(Call&lt;ResponseBody&gt; call, Response&lt;ResponseBody&gt; response)</span> </span>&#123;</span><br><span class="line">              	<span class="comment">//请求成功</span></span><br><span class="line">              	<span class="comment">//响应码 response.code()在[200..300)区间内</span></span><br><span class="line">                <span class="keyword">if</span> (response.isSuccessful()) &#123;</span><br><span class="line">                  	<span class="comment">//数据只能读取一次</span></span><br><span class="line">                    Log.e(TAG, <span class="string">"onResponse: "</span> + response.body().string());</span><br><span class="line">                  	<span class="comment">//第二次打印为空</span></span><br><span class="line">                   	Log.e(TAG, <span class="string">"onResponse: "</span> + response.body().string());</span><br><span class="line">                  	<span class="comment">//记得关闭回收资源</span></span><br><span class="line">                  	response.body().close();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onFailure</span><span class="params">(Call&lt;ResponseBody&gt; call, Throwable t)</span> </span>&#123;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br></pre></td></tr></table></figure>
</li>
<li><p>每个请求对象只能请求一次,但是我们可以利用方法复制一份再请求</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Call&lt;ResponseBody&gt; clone = call.clone();</span><br><span class="line">clone.execute();</span><br></pre></td></tr></table></figure>

<p>​</p>
</li>
</ol>
<h3 id="取消请求"><a href="#取消请求" class="headerlink" title="取消请求"></a>取消请求</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//请求是否已经取消</span></span><br><span class="line">call.isCanceled();</span><br><span class="line"><span class="comment">//请求是否已近完成</span></span><br><span class="line">call.isExecuted();</span><br><span class="line"><span class="comment">//取消请求</span></span><br><span class="line">call.cancel();</span><br></pre></td></tr></table></figure>

<p>:warning:注意:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">new</span> Callback&lt;ResponseBody&gt;() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onResponse</span><span class="params">(Call&lt;ResponseBody&gt; call, Response&lt;ResponseBody&gt; response)</span> </span>&#123;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onFailure</span><span class="params">(Call&lt;ResponseBody&gt; call, Throwable t)</span> </span>&#123;</span><br><span class="line">              <span class="comment">//取消请求,会调用该方法</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br></pre></td></tr></table></figure>

<h2 id="其它注解"><a href="#其它注解" class="headerlink" title="其它注解"></a>其它注解</h2><blockquote>
<p>辅助作用,适用于post,get,可以混合使用</p>
</blockquote>
<h3 id="Body"><a href="#Body" class="headerlink" title="@Body"></a>@Body</h3><blockquote>
<p>可以把参数封装成为一个对象,请求的时候传一个对象就可以了</p>
<p>注意不能可@FormUrlEncoded同时使用</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@POST</span>(<span class="string">"url"</span>)</span><br><span class="line"><span class="function">Call&lt;String&gt; <span class="title">post</span><span class="params">(@Body Bean bean)</span></span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Reviews</span> </span>&#123;</span><br><span class="line">    <span class="keyword">public</span> String var1;</span><br><span class="line">    <span class="keyword">public</span> String var2;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="Path"><a href="#Path" class="headerlink" title="@Path"></a>@Path</h3><blockquote>
<p>根据传递的参数动态改变相对地址,例如分页,分类等</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@GET</span>(<span class="string">"list/&#123;page&#125;"</span>)</span><br><span class="line"><span class="function">Call&lt;BookResponse&gt; <span class="title">getBook</span><span class="params">(@Path(<span class="string">"page"</span>)</span> String page)</span>;</span><br></pre></td></tr></table></figure>

<h3 id="Url"><a href="#Url" class="headerlink" title="@Url"></a>@Url</h3><blockquote>
<p>当我们的地址和basUrl没有关系的时候,可以传递一个完整的地址</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@GET</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> Call&lt;ResponseBody&gt; <span class="title">get</span><span class="params">(@Url String url)</span></span>;</span><br></pre></td></tr></table></figure>

<h3 id="Headers"><a href="#Headers" class="headerlink" title="@Headers"></a>@Headers</h3><blockquote>
<p>给请求添加请求头</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Headers</span>(&#123;	<span class="string">"Accept: application/vnd.yourapi.v1.full+json"</span>,</span><br><span class="line">        	<span class="string">"User-Agent: Your-App-Name"</span> &#125;)</span><br><span class="line"> <span class="meta">@GET</span>(<span class="string">"url"</span>)</span><br><span class="line"><span class="function">Call&lt;BookSearchResponse&gt; <span class="title">getSearchBooks</span><span class="params">(@Query(<span class="string">"var"</span>)</span> String <span class="keyword">var</span>)</span>;</span><br></pre></td></tr></table></figure>

<h2 id="上传文件"><a href="#上传文件" class="headerlink" title="上传文件"></a>上传文件</h2><ol>
<li><p>单张图片上传</p>
<blockquote>
<p>@Multipart表示表单上传数据</p>
<p>@Part后接参数</p>
</blockquote>
<ul>
<li>请求接口</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Multipart</span></span><br><span class="line"><span class="meta">@POST</span>(url)</span><br><span class="line"><span class="function">Call&lt;ResponseBody&gt; <span class="title">upload</span><span class="params">(@Part MultipartBody.Part img)</span></span>;</span><br></pre></td></tr></table></figure>

<ul>
<li>创建参数和请求</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">File file = <span class="keyword">new</span> File(Environment.getExternalStorageDirectory(), <span class="string">"xxx.jpg"</span>);</span><br><span class="line"><span class="comment">//构造请求体</span></span><br><span class="line">RequestBody requestBody = RequestBody.create(MediaType.parse(<span class="string">"multipart/form-data"</span>), file);</span><br><span class="line">MultipartBody.Part part = MultipartBody.Part.createFormData(<span class="string">"img"</span>, file.getName(), requestBody);</span><br><span class="line"></span><br><span class="line">UploadApi uploadApi = retrofit.create(UploadApi<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">Call call = uploadApi.upload( part);</span><br></pre></td></tr></table></figure>
</li>
<li><p>多图以及文字上传</p>
<ul>
<li>请求接口</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">@Multipart</span><br><span class="line">@POST(url)</span><br><span class="line">Call&lt;ResponseBody&gt; upload(@Part() List&lt;MultipartBody.Part&gt; imgs,@Part String var);</span><br></pre></td></tr></table></figure>

<ul>
<li>创建参数和请求</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">List&lt;MultipartBody.Part&gt; parts = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">File file1 = <span class="keyword">new</span> File(Environment.getExternalStorageDirectory(), <span class="string">"1.jpg"</span>);</span><br><span class="line">File file2 = <span class="keyword">new</span> File(Environment.getExternalStorageDirectory(), <span class="string">"2.jpg"</span>);</span><br><span class="line"><span class="comment">//构造请求体</span></span><br><span class="line">RequestBody requestBody1 = RequestBody.create(MediaType.parse(<span class="string">"multipart/form-data"</span>), file1);</span><br><span class="line">MultipartBody.Part part1 = MultipartBody.Part.createFormData(<span class="string">"img1"</span>, file1.getName(), requestBody1);</span><br><span class="line"></span><br><span class="line">RequestBody requestBody2 = RequestBody.create(MediaType.parse(<span class="string">"multipart/form-data"</span>), file2);</span><br><span class="line">MultipartBody.Part part2 = MultipartBody.Part.createFormData(<span class="string">"img2"</span>, file2.getName(), requestBody2);</span><br><span class="line"></span><br><span class="line">parts.add(part1);</span><br><span class="line">parts.add(part2);</span><br><span class="line"></span><br><span class="line">UploadApi uploadApi = retrofit.create(UploadApi<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">Call call = uploadApi.upload(parts,<span class="string">"var"</span>);</span><br></pre></td></tr></table></figure>

</li>
</ol>
<h2 id="强大的拦截器"><a href="#强大的拦截器" class="headerlink" title="强大的拦截器"></a>强大的拦截器</h2><blockquote>
<p>拦截器其实是okhttp的扩展用法,所以拦截器都是给okhttpClien添加,然后把okhttpClient设置到retrofit</p>
</blockquote>
<h3 id="日志拦截器"><a href="#日志拦截器" class="headerlink" title="日志拦截器"></a>日志拦截器</h3><blockquote>
<p>官方提供了一个打印日志的库</p>
</blockquote>
<ol>
<li><p>添加依赖</p>
<figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">compile <span class="string">'com.squareup.okhttp3:logging-interceptor:3.8.1'</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>创建</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">HttpLoggingInterceptor logging = <span class="keyword">new</span> HttpLoggingInterceptor();</span><br><span class="line">logging.setLevel(HttpLoggingInterceptor.Level.BODY);</span><br><span class="line">OkHttpClient client = <span class="keyword">new</span> OkHttpClient.Builder()</span><br><span class="line">	.addInterceptor(logging)</span><br><span class="line">	.addInterceptor(<span class="keyword">new</span> CustomerInterceptor())</span><br><span class="line">	.build();</span><br></pre></td></tr></table></figure>
</li>
<li><p>设置</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">retrofit = <span class="keyword">new</span> Retrofit.Builder()</span><br><span class="line">               .baseUrl(<span class="string">"url"</span>)</span><br><span class="line">               .addConverterFactory(GsonConverterFactory.create())</span><br><span class="line">               .client(client)</span><br><span class="line">               .build();</span><br></pre></td></tr></table></figure>

</li>
</ol>
<h3 id="自定义拦截器-添加统一参数"><a href="#自定义拦截器-添加统一参数" class="headerlink" title="自定义拦截器,添加统一参数"></a>自定义拦截器,添加统一参数</h3><blockquote>
<p>自定义接口都是继承Retrofit的拦截器类然后自己改写</p>
<p>下面这个就是继承拦截器然后获取请求,在请求的基础上复制一个请求,给请求添加统一的参数</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CustomerInterceptor</span> <span class="keyword">implements</span> <span class="title">Interceptor</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Response <span class="title">intercept</span><span class="params">(Chain chain)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">        Request request = chain.request();</span><br><span class="line">        HttpUrl httpUrl = request.url().newBuilder()</span><br><span class="line">                .addQueryParameter(<span class="string">"token"</span>, <span class="string">"xxxx-xxx-xxx-xxx"</span>)</span><br><span class="line">                .addQueryParameter(<span class="string">"deviceType"</span>,<span class="string">"android"</span>)</span><br><span class="line">                .build();</span><br><span class="line">        request = request.newBuilder().url(httpUrl).build();</span><br><span class="line">        <span class="keyword">return</span> chain.proceed(request);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">client.addInterceptor(<span class="keyword">new</span> CustomerInterceptor())</span><br></pre></td></tr></table></figure>

<h2 id="结语"><a href="#结语" class="headerlink" title="结语"></a>结语</h2><p>这一次只是初步的记录了retrofit的简单使用,欢迎大家吐槽.</p>
<p>下一步应该了解如何与Rxjava的结合使用(没办法,现在你说你不会这两个都会感觉不好意思).</p>
<h2 id="参考文章"><a href="#参考文章" class="headerlink" title="参考文章"></a>参考文章</h2><p><a href="http://duanyytop.github.io/2016/08/06/Retrofit%E7%94%A8%E6%B3%95%E8%AF%A6%E8%A7%A3/?utm_source=tuicool&utm_medium=referral" target="_blank" rel="noopener" title="Retrofit用法详解">http://duanyytop.github.io/2016/08/06/Retrofit%E7%94%A8%E6%B3%95%E8%AF%A6%E8%A7%A3/?utm_source=tuicool&amp;utm_medium=referral</a></p>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/blog/tags/android/" rel="tag"># android</a>
              <a href="/blog/tags/%E7%BD%91%E7%BB%9C/" rel="tag"># 网络</a>
              <a href="/blog/tags/retrofit/" rel="tag"># retrofit</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/blog/2017/07/29/book1/" rel="prev" title="开始写博客啦">
      <i class="fa fa-chevron-left"></i> 开始写博客啦
    </a></div>
      <div class="post-nav-item">
    <a href="/blog/2017/08/10/andoridM/" rel="next" title="andoridM">
      andoridM <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#开始使用"><span class="nav-number">1.</span> <span class="nav-text">开始使用</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#初始化Retrofit"><span class="nav-number">2.</span> <span class="nav-text">初始化Retrofit</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#创建Get请求"><span class="nav-number">3.</span> <span class="nav-text">创建Get请求</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#创建post请求"><span class="nav-number">4.</span> <span class="nav-text">创建post请求</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#如何请求"><span class="nav-number">5.</span> <span class="nav-text">如何请求</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#发起请求"><span class="nav-number">5.1.</span> <span class="nav-text">发起请求</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#取消请求"><span class="nav-number">5.2.</span> <span class="nav-text">取消请求</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#其它注解"><span class="nav-number">6.</span> <span class="nav-text">其它注解</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Body"><span class="nav-number">6.1.</span> <span class="nav-text">@Body</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Path"><span class="nav-number">6.2.</span> <span class="nav-text">@Path</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Url"><span class="nav-number">6.3.</span> <span class="nav-text">@Url</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Headers"><span class="nav-number">6.4.</span> <span class="nav-text">@Headers</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#上传文件"><span class="nav-number">7.</span> <span class="nav-text">上传文件</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#强大的拦截器"><span class="nav-number">8.</span> <span class="nav-text">强大的拦截器</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#日志拦截器"><span class="nav-number">8.1.</span> <span class="nav-text">日志拦截器</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#自定义拦截器-添加统一参数"><span class="nav-number">8.2.</span> <span class="nav-text">自定义拦截器,添加统一参数</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#结语"><span class="nav-number">9.</span> <span class="nav-text">结语</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#参考文章"><span class="nav-number">10.</span> <span class="nav-text">参考文章</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="二松"
      src="/blog/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">二松</p>
  <div class="site-description" itemprop="description">good good study day day up.</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/blog/archives/">
        
          <span class="site-state-item-count">27</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/blog/categories/">
          
        <span class="site-state-item-count">7</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/blog/tags/">
          
        <span class="site-state-item-count">32</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">二松</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/blog/lib/anime.min.js"></script>
  <script src="/blog/lib/velocity/velocity.min.js"></script>
  <script src="/blog/lib/velocity/velocity.ui.min.js"></script>

<script src="/blog/js/utils.js"></script>

<script src="/blog/js/motion.js"></script>


<script src="/blog/js/schemes/pisces.js"></script>


<script src="/blog/js/next-boot.js"></script>




  













<script>
if (document.querySelectorAll('pre.mermaid').length) {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/mermaid@8/dist/mermaid.min.js', () => {
    mermaid.initialize({
      theme    : 'forest',
      logLevel : 3,
      flowchart: { curve     : 'linear' },
      gantt    : { axisFormat: '%m/%d/%Y' },
      sequence : { actorMargin: 50 }
    });
  }, window.mermaid);
}
</script>


  

  

</body>
</html>
